<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/skincheckTicket'
import detailStore from '@/store/modules/NewCacheData'
import { GetOptionData as GetVoucherOption } from '@/api/modules/voucher'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const SkinKeyList = [{
  key: 'Game_Lian_1',
  label: '连连看第1关',
},
{
  key: 'Game_Lian_2',
  label: '连连看第2关',
}]

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  skinKey: '',
  ticketId: 0,
  ticketDesp: '',
  linkUrl: '',
  status: 0,
})

// 选择器选项Json
const OptionJson = reactive({
  TicketOption: [],
})

const id = route.query.id as string

// 提交
async function SubmitData() {
  const params = { ...ruleForm.value }
  if (id) {
    // 编辑
    params.id = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'skincheckLlksentIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.emptyFormData('skincheckLlksentFrom')
        router.push({ name: 'skincheckLlksentIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('skincheckLlksentFrom')
  }

  // 获取所有卡券
  const voucherData: any = await GetVoucherOption()
  if (voucherData.succeeded) {
    OptionJson.TicketOption = voucherData.data
    nextTick(() => {
      OptionJson.TicketOption = voucherData.data
    })
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('skincheckLlksentFrom', newValue)
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="6">
            <ElFormItem label="卡券">
              <el-select v-model="ruleForm.ticketId" placeholder="请选择卡券" filterable>
                <el-option
                  v-for="items in (OptionJson.TicketOption as any[])" :key="items.id" :label="`${items.id}-${items.name}`" :value="items.id"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="6">
            <ElFormItem label="游戏关卡">
              <el-select v-model="ruleForm.skinKey" placeholder="请选择游戏关卡">
                <el-option
                  v-for="item in SkinKeyList"
                  :key="item.key"
                  :label="`${item.label}`"
                  :value="item.key"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="6">
            <ElFormItem label="跳转路径（为空则跳转至券关联商品集合页）">
              <el-input v-model="ruleForm.linkUrl" placeholder="请输入跳转路径" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="6">
            <ElFormItem label="状态">
              <el-switch
                v-model="ruleForm.status"
                active-text="启用"
                inactive-text="停用"
                :active-value="1"
                :inactive-value="-1"
              />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="券描述">
              <el-input v-model="ruleForm.ticketDesp" placeholder="请输入券描述" type="textarea" />
            </ElFormItem>
          </ElCol> -->
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
